//
//  CLQueue.m
//  Charles
//
//  Created by Leo on 2019/6/27.
//  Copyright © 2019 charles. All rights reserved.
//

#import "CLQueue.h"

@interface CLArrayQueue ()

@property (nonatomic, assign) NSInteger capacity;   // 队容量
@property (nonatomic, assign) NSInteger head;       // 队头下标
@property (nonatomic, assign) NSInteger tail;       // 队尾下标
@property (nonatomic, assign) NSInteger *items;

@end

@implementation CLArrayQueue

- (instancetype)initWithCapacity:(NSInteger)capacity {
    if (self = [super init]) {
        self.capacity = capacity;
        self.head = 0;
        self.tail = 0;
        [self setupQueuecCapacity];
    }
    return self;
}

- (void)setupQueuecCapacity {
    self.items = malloc(sizeof(NSInteger) *self.capacity);
}

- (BOOL)enqueue:(NSInteger)item {
    // 如果队列末尾没有空间了
    if (self.capacity == self.tail) {
        // 如果head==0 且 队列末尾没空间了说明队列满了
        if (self.head == 0) {
            NSLog(@"队列已经满了...");
            return NO;
        }
        // 否则数据搬移,就是将队列中的数据移动到从0开始的位置
        for (NSInteger i = self.head; i < self.tail; i++) {
            self.items[i - self.head] = self.items[i];
        }
        // 搬移完了之后,更新head 和 tail的下标位置
        self.tail -= self.head;
        self.head = 0;
    }
    NSLog(@"入队成功了...");
    self.items[self.tail] = item;
    self.tail++;
    return YES;
}

- (NSInteger)dequeue {
    if (self.tail == self.head) {
        NSLog(@"队列已经空了...");
        return 0;
    }
    NSInteger item = self.items[self.head];
    self.head++;
    NSLog(@"出队成功了...");
    return item;
}

@end
